import React, { Component } from 'react';
import { Table, Popconfirm, message, Tooltip } from 'antd';
import CouponHeader from '../../../components/Coupon/CouponHeader/index'
import ProvideModal from '../../../components/Coupon/ProvideModal/index'
import EditCouponModal from '../../../components/Coupon/EditCouponModal/index'
import couponApi from '../../../api/coupon'
import './index.scss'
import filter from '../../../utils/Filters'
  
class Coupon extends Component {
  
  state = { 
    modalData:{
      visible: false
    },
    editModalData:{
      visible: false,
      countLimit:0,
      productIds:[]
    },
    editId:'',//要编辑的优惠券id
    searchData:{
      page:1,
      rows:30,
      name:'',
      code:'',
      type:'',
      createUserName:'',
      status:'',
    },
    couponInfoArray:{},
    isEdit:false,//是否提交优惠券编辑
  }

  // 表格分页对象
  pageObj = {
    size:"small",
    total:0,
    pageSize:this.state.searchData.rows,
    showSizeChanger:true,
    showQuickJumper:true,
    showTotal:()=>`共 ${this.props.couponListTotal} 条`,
    onChange:(page)=>{    
      this.setState({
        searchData:Object.assign({},this.state.searchData,{
          page
        })
      },()=>{
        this.handleCheck();
      })
    },
    onShowSizeChange: (page, rows)=> {
      let _obj = Object.assign({},this.state.searchData,{
        rows:rows
      });                
      this.setState({
        searchData:_obj
      },()=>{
          this.handleCheck();
        }
      )
    }  
  }  

  columns = [
    { title: '编码', dataIndex: 'code', key: 'code', width: 80, },
    { title: '类型', dataIndex: 'couponTypeStr', key: 'couponTypeStr', },
    { title: '名称', dataIndex: 'name', key:"name",},
    { title: '金额', dataIndex: 'discount', key: 'discount', width: 80, render: (text, record) =>  {
        return <span>{ record.type == 3?record.zkCouponStr:"￥"+record.discount }</span>       
    }},
    { title: '有效期', dataIndex: 'begainTime', key: 'begainTime' , render: (text, record) =>  {
      if(record.begainTime !== ""){
        return (
          <div style={{ width:120 }}>
            <div>起：{ record.begainTime }</div>
            <div>至：{ record.endTime }</div>
          </div>
        )
      }else{
        return <span>不限期</span>        
      }
    }},
    { title: '可领取组织', dataIndex: 'orgName', key: 'orgName', render: (text, record) => {
      return ( 
        <div  className="tool-tip">
          <Tooltip title={ record.orgName }>
            <p>{ record.orgName }</p>
          </Tooltip>
        </div>
       )
    }  },
    { title: '已领取', dataIndex: 'hasGet', key: 'hasGet',  },
    { title: '已使用', dataIndex: 'hasUse', key: 'hasUse',  },
    { title: '创建人', dataIndex: 'createUserName', key: 'createUserName',  },
    { title: '绑定名片', dataIndex: 'bindCardStr', key: 'bindCardStr',  },
    { title: '时间状态', dataIndex: 'timeStatusStr', key: 'timeStatusStr',  },
    { title: '操作状态', dataIndex: 'operStatusStr', key: 'operStatusStr',  },
    { title: '操作', dataIndex: '', key: '6',  render: (text, record) => (        
        <div style={{ width:72 }} className={['table-operation', (record.dateStatus === 2 || record.status === 2) && 'dn'].join(' ')}>        
          <a className={ record.status === 2 ?'dn':'' } onClick={this.handleEdit.bind(this,record)}>编辑</a>
          <Popconfirm className={ record.status !== 0 ? 'dn':'' } title="确定要删除该优惠券吗?" onConfirm={this.handleDelete.bind(this,record)} okText="确定" cancelText="取消">
            <a>删除</a>
          </Popconfirm>
          <a className={ record.status !== 0 ?'dn':'' } onClick={this.showModal.bind(this,record.id)}>发放</a>
          <Popconfirm className={ record.status === 2 ?'dn':'' }title="是否下架优惠券？下架后优惠券不可再领取。" onConfirm={this.handleUndercarriage.bind(this,record)} okText="确定" cancelText="取消">
            <a>下架</a>
          </Popconfirm>
        </div>       
      ), },
  ];

    expandedRowRender = (record) => {      
      const columns = [
        { title: '归属', dataIndex: 'orgName', key: 'orgName' },
        { title: '券总数', dataIndex: 'countLimit', key: 'countLimit' },
        { title: '已领取',dataIndex: 'hasGet', key: 'hasGet', },
        { title: '已使用', dataIndex: 'hasUse', key: 'hasUse' },
        { title: '库存', dataIndex: 'storage', key: 'storage' },
        { title: '流水', dataIndex: 'payMoney', key: 'payMoney' },
        { title: '优惠总额', dataIndex: "couponMoney", key: 'couponMoney',render: (text, record) => (
          '￥'+record.couponMoney
         ) },
        { title: '使用率', dataIndex: "useRate", key: 'useRate' },
        { title: '优惠费比', dataIndex: "couponRate", key: 'couponRate' },
      ];  
      return (
        <Table
          columns={columns}
          dataSource={this.state.couponInfoArray.hasOwnProperty(record.id)?this.state.couponInfoArray[record.id]:[]}
          pagination={false}
        />
      );           
    };    
  componentWillMount(){
    console.log(this.props)        
    this.handleCheck();
    this.props.onCheckOrgList();
    //获取业务层次
    if(this.props.businessLevelSelect.length == 0){
      this.props.onCheckBusinessLevelSelect({});     
    }  
  }

  componentWillReceiveProps(newProps){   
    console.log(JSON.stringify(newProps.couponInfo))
    this.pageObj.total = newProps.couponListTotal;  
    this.pageObj.pageSize = this.state.searchData.rows;
    this.setState({
      couponInfoArray:newProps.couponInfo
    })

    //如果编辑成功，则关闭编辑优惠券弹窗
    if(newProps.editCouponStatus && this.state.isEdit){
      this.setState({
        modalData:{
          visible: false
        },
        editModalData:{
          visible: false
        },
        isEdit:false
      });
    }
  }

  //方法区域
  //点击编辑优惠券
  handleEdit = (data)=>{
    this.props.onCheckCouponProductList({
      id:data.id
    })    
    console.log(data.countLimit)
    this.setState({
      editModalData:{
        visible: true,
        countLimit:data.countLimit,
        productIds:data.productIds,
        couponId:data.id
      },
      editId:data.id
    })
  }

  //获取表格数据
  handleCheck = (data) =>{
    this.setState({
      searchData:Object.assign({},this.state.searchData,data)
    },()=>{
      this.props.onCheckClick(this.state.searchData)
    })
    
  }
  
  //删除优惠券
  handleDelete = (data) =>{
    couponApi.deleteCoupon({id:data.id},()=>{
      message.success('删除成功');
      this.handleCheck();
    })
  }  

  //下架优惠券
  handleUndercarriage = (data) =>{
    let _obj = Object.assign({},{
      status:2,
      id:data.id,
      searchData:this.state.searchData
    })
    this.props.onHandleEdit(_obj)
  }  
  // 展示modal
  showModal = (id) => {
    this.setState({
      modalData:{
        visible: true
      },
      editId:id
    });
  }
  // 编辑优惠券
  handleOk = (data) => {    
    this.setState({
      isEdit:true
    })
    this.props.onHandleEdit({
      id:this.state.editId,
      ...data,
      searchData:this.state.searchData
    })
  }
  handleCancel = () => {
    this.setState({
      modalData:{
        visible: false
      },
      editModalData:{
        visible: false
      },
    });
  }
  render() {
    const state = this.state;
    return (
        <div>
            <CouponHeader onHandleCheck={ this.handleCheck } />
            <Table
                pagination={false}
                columns={this.columns}
                scroll={{ x: 1300 }}
                expandedRowRender={this.expandedRowRender}
                dataSource={this.props.couponList}
                pagination={this.pageObj}
                rowKey="id"                
                onExpand={(expanded, record)=>{
                  if(expanded){
                    if(!this.state.couponInfoArray.hasOwnProperty(record.id)){
                      this.props.onExpandClick({id:record.id})
                    }
                  }                  
                }}
            />        
            {/* 发放优惠券弹窗 */}
            <ProvideModal modalData={state.modalData} orgList={this.props.orgList} handleOk={this.handleOk.bind(this)} handleCancel={this.handleCancel.bind(this)}/>            
            {/* 编辑优惠券 */}
            <EditCouponModal 
              modalData={state.editModalData} 
              businessLevelSelect={ this.props.businessLevelSelect } 
              productList={ this.props.productList }
              productListTotal={ this.props.productListTotal }  
              couponProductList={ this.props.couponProductList } 
              onCheckProduct={ (data)=> this.props.onCheckProduct(data) } 
              handleOk={this.handleOk.bind(this)} 
              handleCancel={this.handleCancel.bind(this)}
            />
            
        </div>
        )
    }
}
export default Coupon;